<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="reg-btn">注册用户</button>
    <script>
        // 1.定义myAxios函数，接受配置对象，返回Promise
        function myAxios(config) {
            return new Promise((resolve, reject) => {
                if (config.params) {
                    // 使用URLSearchParams转换
                    const paramsObj = new URLSearchParams(config.params)
                    const queryString = paramsObj.toString()
                    config.url += `?${queryString}`
                }
                const xhr = new XMLHttpRequest()
                xhr.open(config.method || 'GET', config.url)
                xhr.addEventListener('loadend', () => {
                    // 判断调用是否成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.response))
                    } else {
                        reject(new Error(xhr.response))
                    }
                })
                // 判断是否有dta选项，携带请求体
                if (config.data) {
                    const jsonStr = JSON.stringify(config.data)
                    xhr.setRequestHeader('Content-Type', 'application/json')
                    xhr.send(jsonStr)
                } else {
                    xhr.send()
                }
            })
        }

        document.querySelector('.reg-btn').addEventListener('click', () => {
            myAxios({
                url: 'http://hmajax.itheima.net/api/register',
                method: 'POST',
                data: {
                    username: 'itheima999',
                    password: '666666'
                }
            }).then(result => {
                console.log(result);
            }).catch(error => {
                console.dir(error)
            })
        })



    </script>
</body>

</html>